package com.liyunc.demo.bundle.web.config.handler;

import com.liyunc.demo.comp.common.exceptions.ApplicationException;
import com.liyunc.demo.comp.common.exceptions.enums.ErrorCode;
import com.liyunc.demo.comp.common.rest.response.GeneralResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author liyuncong
 * @version 1.0
 * @file ApplicationExceptionHandler
 * @brief ApplicationExceptionHandler
 * @details ApplicationExceptionHandler
 * @date 2022/5/21
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                        NAME               DESCRIPTION
 * 2022/5/21                     liyuncong          Created
 */
@Log4j2
@RestControllerAdvice
public class ApplicationExceptionHandler {

    @ExceptionHandler(value = {Exception.class, Throwable.class})
    public GeneralResponse<ErrorCode> handlerException(Exception exception) {
        exception.printStackTrace();
        if (exception instanceof ApplicationException) {
            int code = ((ApplicationException) exception).getCode();
            String message = exception.getMessage();
            log.error("[全局异常拦截]ApplicationException: errorCode {},errorMessage {}",
                code, message);
            return GeneralResponse.of(code, message, null);
        } else {
            Long code = ErrorCode.SERVER_ERROR.getCode();
            String message = ErrorCode.SERVER_ERROR.getMessage();
            log.error("[全局异常拦截]Exception: errorMessage {}", exception.getMessage());
            return GeneralResponse.of(code.intValue(), message, null);
        }
    }
}
